//
//  MyUserInfoViewController.swift
//  koolcar
//
//  Created by xiantian on 2023/11/2.
//
 
import UIKit
import RxSwift
import RxCocoa
 
class MyUserInfoViewController: BaseViewController {
    var emptyView: LYEmptyView!
    var titleLab: UILabel!
    var tableView: BaseTableView!
    var bottomBtn: UIButton!
    var dataCellArray: [UITableViewCell] = []
    var dataModel = UserInfoObj()
    var disBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.title = MMLocalizedString("profile_title", comment: "我的资料")
        self.navBar.backgroundColor = .white
        self.navBar.wr_setBottomLineHidden(hidden: true)
        
        tableView = BaseTableView.init(frame: CGRect.zero, style: .plain)
        tableView.register(AddUserGenderCell.self, forCellReuseIdentifier: "AddUserGenderCell")
        tableView.register(AddUserFullNameCell.self, forCellReuseIdentifier: "AddUserFullNameCell")
        tableView.register(AddUserTFCell.self, forCellReuseIdentifier: "emailCell")
        tableView.register(AddUserTFCell.self, forCellReuseIdentifier: "birthCell")
        tableView.register(AddUserTFCell.self, forCellReuseIdentifier: "phoneCell")
        tableView.register(AddUserTFCell.self, forCellReuseIdentifier: "passwordCell")
        tableView.register(AddUserTFCell.self, forCellReuseIdentifier: "password1Cell")
        tableView.register(AddUserTFCell.self, forCellReuseIdentifier: "couponCell")
        tableView.register(AddUserTFCell.self, forCellReuseIdentifier: "AddUserTFCell")
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white
        tableView.separatorStyle = .none
        tableView.delaysContentTouches = true
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 54
        tableView.estimatedSectionFooterHeight = 2
        tableView.estimatedSectionHeaderHeight = 2
        view.addSubview(tableView)
        self.setUpNoData()
        
        bottomBtn = UIButton()
        bottomBtn.setup_titleLabel(text: MMLocalizedString("add_done", comment: "完成"))
        bottomBtn.setup_titleColor(color: UIColor.white)
        bottomBtn.setBackgroundImage(UIImage.image(withColor: Theme.mainColor), for: .normal)
        bottomBtn.setBackgroundImage(UIImage.image(withColor: Theme.mainColorHighLightColor), for: .highlighted)
        bottomBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        bottomBtn.layer.cornerRadius = 8
        bottomBtn.layer.masksToBounds = true
        bottomBtn.addTarget(self, action: #selector(bottomBtnAction), for: .touchUpInside)
        view.addSubview(bottomBtn)
        
        self.dataModel.removeAllTip()
        self.addSnpLayout()
        self.fetchGetUserInfo()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
   
    override func backAction() {
        super.backAction()
        //跳到指定界面
        let registerVC = RegisterViewController()
        var targetVC : UIViewController!
        for controller in self.navigationController!.viewControllers {
            if controller.isKind(of: registerVC.classForCoder) {
                targetVC = controller
            }
        }
        if targetVC != nil {
            self.navigationController?.popToViewController(targetVC, animated: true)
        }
    }
    
    func addSnpLayout(){
        tableView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(NavBarHight + 20)
        }
        
        let marginBottom = IphoneXMarginBottom > 1 ? IphoneXMarginBottom : 4
        bottomBtn.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.height.equalTo(46)
            make.top.equalTo(tableView.snp.bottom).offset(10)
            make.bottom.equalTo(-marginBottom)
        }
    }
    
    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_empty", titleStr: MMLocalizedString("no_more_data", comment: "暂时没有数据"), detailStr: "", btnTitleStr: "") {
            
        }
        emptyView?.subViewMargin = 28;
        emptyView?.contentViewOffset = -100
        self.tableView.ly_emptyView = self.emptyView
    }
    
    ///空视图
    func willShowEmptyView() {
        if self.dataCellArray.count == 0 {
            self.tableView.mj_footer?.isHidden = true
            self.emptyView.isHidden = false
            self.emptyView?.titleStr = MMLocalizedString("no_data", comment: "暂无数据")
        }else{
            self.emptyView.isHidden = true
            self.emptyView?.titleStr = ""
        }
    }
    
    ///获取用户信息
    private func fetchGetUserInfo(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.memberGetDetail, objectType: UserInfoResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! UserInfoResModel
            if resultObj.code == "1" {
                let tempData = resultObj.data
                var tempUserObj = UserInfoObj()
                tempUserObj.lastName = tempData?.lastName ?? ""
                tempUserObj.firstName = tempData?.firstName ?? ""
                tempUserObj.email = tempData?.email ?? ""
                tempUserObj.phone = tempData?.phone ?? ""
                tempUserObj.birthday = tempData?.birthday ?? ""
                tempUserObj.gender = "\(tempData?.gender ?? 0)"
                tempUserObj.name = tempData?.userName ?? ""
                self.dataModel = tempUserObj
                self.initailData()
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
            self.willShowEmptyView()
        } error: { err in
            self.willShowEmptyView()
            self.view.handleLoading()
            self.view.makeToastBottom(message: err?.domain ?? MMLocalizedString("request_failed", comment: "请求失败，请稍候再试"))
        }
    }
    
    ///初始化cell
    func initailData(){
        self.dataCellArray = []
        //姓别
        if let genderCell = self.tableView.dequeueReusableCell(withIdentifier: "AddUserGenderCell") as? AddUserGenderCell {
            if let index = Int(self.dataModel.gender) {
                genderCell.segmentBtn.selectedSegmentIndex = index
            }else{
                genderCell.segmentBtn.selectedSegmentIndex = 0
            }
            genderCell.showTopTitleLab()
            genderCell.callBack = {[weak self] index in
                self?.dataModel.gender = "\(index)"
            }
            dataCellArray.append(genderCell)
        }
        
        //名字 + 姓氏
        if let nameCell = self.tableView.dequeueReusableCell(withIdentifier: "AddUserFullNameCell") as? AddUserFullNameCell {
            nameCell.showTopTitleLab()
            nameCell.lastNameTF.placeholder = MMLocalizedString("add_input_first_name", comment: "请输入名字")
            nameCell.firstNameTF.placeholder = MMLocalizedString("add_input_last_name", comment: "请输入姓氏")
            nameCell.lastNameTF.text = self.dataModel.lastName
            nameCell.firstNameTF.text = self.dataModel.firstName
            nameCell.firstNameTF.keyboardType = .default
            nameCell.firstNameTF.returnKeyType = .done
            nameCell.lastNameTF.keyboardType = .default
            nameCell.lastNameTF.returnKeyType = .done
            nameCell.lastNameTF.rx.text.orEmpty.subscribe { txt in
                self.dataModel.lastName = txt
            }.disposed(by: self.disBag)
            
            nameCell.firstNameTF.rx.text.orEmpty.subscribe { txt in
                self.dataModel.firstName = txt
            }.disposed(by: self.disBag)
            
            self.dataModel.familyNameTip
                .bind(to: nameCell.firstMsgLab.rx.text)
                .disposed(by: self.disBag)
            
            self.dataModel.lastNameTip
                .bind(to: nameCell.lastMsgLab.rx.text)
                .disposed(by: self.disBag)
            
            //绑边框颜色
            self.dataModel.lastNameTip.map { value in
                return value == "" ? Theme.tfBorderColor : Theme.tfBorderRedColor
            }.subscribe(onNext: { color in
                nameCell.lastNameTF.layer.borderColor = color.cgColor
            }).disposed(by: self.disBag)
            
            //绑边框颜色
            self.dataModel.familyNameTip.map { value in
                return value == "" ? Theme.tfBorderColor : Theme.tfBorderRedColor
            }.subscribe(onNext: { color in
                nameCell.firstNameTF.layer.borderColor = color.cgColor
            }).disposed(by: self.disBag)
            
            //名字编辑结束时，校验一次
            nameCell.lastNameTF.rx.controlEvent(UIControlEvents.editingDidEnd).subscribe {[weak self] _ in
                let lastname = self?.dataModel.lastName ?? ""
                if lastname == "" {
                    self?.dataModel.lastNameTip.accept(MMLocalizedString("add_input_first_name", comment: "请输入名字"))
                }else{
                    self?.dataModel.lastNameTip.accept("")
                }
                DispatchQueue.main.async {
                    self?.tableView.beginUpdates()
                    self?.tableView.endUpdates()
                }
            }.disposed(by: self.disBag)
            
            //姓氏编辑结束时，校验一次
            nameCell.firstNameTF.rx.controlEvent(UIControlEvents.editingDidEnd).subscribe {[weak self] _ in
                //姓氏
                let firstname = self?.dataModel.firstName ?? ""
                if firstname == "" {
                    self?.dataModel.familyNameTip.accept(MMLocalizedString("add_input_last_name", comment: "请输入姓氏"))
                }else{
                    self?.dataModel.familyNameTip.accept("")
                }
                DispatchQueue.main.async {
                    self?.tableView.beginUpdates()
                    self?.tableView.endUpdates()
                }
            }.disposed(by: self.disBag)
            
            //回车键关闭键盘
            nameCell.lastNameTF.rx.controlEvent(UIControlEvents.editingDidEndOnExit).subscribe { _ in
                nameCell.lastNameTF.resignFirstResponder()
            }.disposed(by: self.disBag)
            
            nameCell.firstNameTF.rx.controlEvent(UIControlEvents.editingDidEndOnExit).subscribe { _ in
                nameCell.firstNameTF.resignFirstResponder()
            }.disposed(by: self.disBag)
            dataCellArray.append(nameCell)
        }
        
        
        //email
        if let emailCell = self.tableView.dequeueReusableCell(withIdentifier: "emailCell") as? AddUserTFCell {
            emailCell.showTopTitleLab(txt: MMLocalizedString("profile_email", comment: "电子邮件"))
            emailCell.textField.placeholder = MMLocalizedString("add_input_email", comment: "请填写电邮地址（选填）")
            emailCell.textField.text = self.dataModel.email
            emailCell.textField.rx.text.orEmpty.subscribe { txt in
                self.dataModel.email = txt
            }.disposed(by: self.disBag)
            
            emailCell.textField.rx.controlEvent(UIControlEvents.editingDidEndOnExit).subscribe { _ in
                //不处理
            }.disposed(by: self.disBag)
            
            self.dataModel.emailTip
                .bind(to: emailCell.msgLab.rx.text)
                .disposed(by: self.disBag)
            
            //email绑边框颜色
            self.dataModel.emailTip.map { value in
                return value == "" ? Theme.tfBorderColor : Theme.tfBorderRedColor
            }.subscribe(onNext: { color in
                emailCell.textField.layer.borderColor = color.cgColor
            }).disposed(by: self.disBag)
            
            //编辑结束时，校验一次
            emailCell.textField.rx.controlEvent(UIControlEvents.editingDidEnd).subscribe {[weak self] _ in
                let email = self?.dataModel.email ?? ""
                if email != "" && XTManageCenter.isEmail(email: email) == false {
                    self?.dataModel.emailTip.accept(MMLocalizedString("add_input_real_email", comment: "请输入正确的电邮地址"))
                }else{
                    self?.dataModel.emailTip.accept("")
                }
                DispatchQueue.main.async {
                    self?.tableView.beginUpdates()
                    self?.tableView.endUpdates()
                }
            }.disposed(by: self.disBag)
            dataCellArray.append(emailCell)
        }
        
        
        //手机号码
        if let phoneCell = self.tableView.dequeueReusableCell(withIdentifier: "phoneCell") as? AddUserTFCell {
            phoneCell.isUserInteractionEnabled = false
            phoneCell.textField.backgroundColor = Theme.eColor
            phoneCell.textField.placeholder = MMLocalizedString("regist_please_enter_phone", comment: "请输入手机号码")
            phoneCell.showTopTitleLab(txt: MMLocalizedString("profile_phone", comment: "手机号码"))
            phoneCell.textField.text = self.dataModel.phone
            phoneCell.textField.clearButtonMode = .whileEditing
            phoneCell.textField.textColor = Theme.lineSixColor
            phoneCell.textField.rx.text.orEmpty.subscribe { txt in
                self.dataModel.phone = txt
            }.disposed(by: self.disBag)
            
            self.dataModel.birthdayTip
                .bind(to: phoneCell.msgLab.rx.text)
                .disposed(by: self.disBag)
            
            //手机号绑边框颜色
            self.dataModel.birthdayTip.map { value in
                return value == "" ? Theme.tfBorderColor : Theme.tfBorderRedColor
            }.subscribe(onNext: { color in
                phoneCell.textField.layer.borderColor = color.cgColor
            }).disposed(by: self.disBag)
            dataCellArray.append(phoneCell)
        }
        
        
        //生日
        if let birthCell = self.tableView.dequeueReusableCell(withIdentifier: "birthCell") as? AddUserTFCell {
            birthCell.isUserInteractionEnabled = false
            birthCell.textField.backgroundColor = Theme.eColor
            birthCell.textField.placeholder = MMLocalizedString("add_input_birthday", comment: "请填写出生日期")
            birthCell.showTopTitleLab(txt: MMLocalizedString("profile_birth", comment: "出生日期"))
            birthCell.textField.textColor = Theme.lineSixColor
            birthCell.textField.text = self.dataModel.birthday
            let rightBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 44, height: 44))
            rightBtn.setup_image(image: UIImage.init(named: "icon_day_pick"))
            rightBtn.addTarget(self, action: #selector(self.datePickerBtnAction), for: .touchUpInside)
            birthCell.rightView = rightBtn  //rightView只对uiview生效
            birthCell.textField.rightViewMode = .always
            birthCell.textField.isEnabled = false //禁止编辑
            birthCell.textField.clearButtonMode = .never
            
            birthCell.textField.rx.text.orEmpty.subscribe { txt in
                self.dataModel.birthday = txt
            }.disposed(by: self.disBag)
            
            self.dataModel.birthdayTip
                .bind(to: birthCell.msgLab.rx.text)
                .disposed(by: self.disBag)
            
            //生日绑边框颜色
            self.dataModel.birthdayTip.map { value in
                return value == "" ? Theme.tfBorderColor : Theme.tfBorderRedColor
            }.subscribe(onNext: { color in
                birthCell.textField.layer.borderColor = color.cgColor
            }).disposed(by: self.disBag)
            
            dataCellArray.append(birthCell)
        }
     
          self.tableView.reloadData()
    }
    
    ///选日期
    @objc func datePickerBtnAction(){
        self.view.endEditing(true)
        self.resignFirstResponder()
        guard let cell = self.dataCellArray.first(where: {$0.reuseIdentifier == "birthCell"}) as? AddUserTFCell else {
            return
        }
        
        let datePicker1 = DatePickerView.datePicker(style: .yearMonthDay, scrollToDate: Date()) { date in
            guard let date = date else { return }
            let dateFormat = DateFormatter.init()
            dateFormat.dateFormat = "yyyy-MM-dd"
            let dateStr = dateFormat.string(from: date)
            cell.textField.text = dateStr
            self.dataModel.birthday = dateStr
        }
        let date = Date.date(self.dataModel.birthday, formatter: "yyyy-MM-dd")
        datePicker1.maxLimitDate = Date.date(XTManageCenter.getDateStringNow(), formatter:"yyyy-MM-dd") ?? Date.init()
        datePicker1.scrollToDate = (date == nil ? Date.init() : date)!
        datePicker1.show()
    }
    
    
    ///提交
    /*
     {
     "gender": 0, //称谓 0：女士、1：先生、2：小姐
     "phone": "18999999999", //注册手机号
     "mobileAreaCode": "86", //区号
     "password": "123456", //登录密码
     "firstName": "5", //姓氏
     "lastName": "7", //名字
     "sendType": 1, //默认注册 1
     "code": "27518", //验证码
     "email": "test@qq.com", //邮箱
     "agreeFlag": 1, //是否同意用户资料转移 0否  1 是
     "birthday": "2023-09-09 10:15:34", //生日
     "prizeOrReferralCode": "" //优惠码或邀请码
     }
     */
    @objc func bottomBtnAction(){
        let valid = self.validateFormData()
        if !valid {
            return
        }
        var param: [String: String] = [:]
        param["gender"] = self.dataModel.gender
        param["firstName"] = self.dataModel.firstName //名
        param["lastName"] = self.dataModel.lastName  //姓
        param["email"] = self.dataModel.email
        param["status"] = "1"
        param["sendType"] = "1"

        self.view.showLoadingHUDText()
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.updateUserInfo(param: param), objectType: CommondResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as? CommondResModel
            guard resultObj?.code == "1" else {
                self.view.makeToast(message: resultObj?.msg ?? "")
                return
            }
            self.view.makeToast(message: MMLocalizedString("profile_modify_success", comment: "修改成功"))
            self.perform(#selector(self.handleRegistSuccess), afterDelay: 1.2)
        } error: { err in
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///注册成功后跳转
    @objc func handleRegistSuccess(){
        self.navigationController?.popViewController(animated: true)
    }
    
    ///点击完成按钮时，校验data
    private func validateFormData() -> Bool {
        var valid = true
        //名字
        let lastname = self.dataModel.lastName
        if lastname == "" {
            valid = false
            self.dataModel.lastNameTip.accept(MMLocalizedString("add_input_first_name", comment: "请输入名字"))
        }else{
            self.dataModel.lastNameTip.accept("")
        }
        
        //姓氏
        let firstname = self.dataModel.firstName
        if firstname == "" {
            valid = false
            self.dataModel.familyNameTip.accept(MMLocalizedString("add_input_last_name", comment: "请输入姓氏"))
        }else{
            self.dataModel.familyNameTip.accept("")
        }
        
        //email
        let email = self.dataModel.email
        if email != "" && XTManageCenter.isEmail(email: email) == false {
            valid = false
            self.dataModel.emailTip.accept(MMLocalizedString("add_input_real_email", comment: "请输入正确的电邮地址"))
        }else{
            self.dataModel.emailTip.accept("")
        }
        self.tableView.reloadData()
        return valid
    }
    
}


extension MyUserInfoViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataCellArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 34
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.dataCellArray[indexPath.row]
        cell.selectionStyle = .none
        cell.clipsToBounds = true
        return cell
    }
}

extension MyUserInfoViewController: UIScrollViewDelegate {
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.resignFirstResponder()
        self.view.endEditing(true)
    }
}
